package com.simpleaccount.Cloud;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.simpleaccount.Db.DbUtils;
import com.simpleaccount.Entity.Category;
import com.simpleaccount.Entity.Entry;
import com.simpleaccount.Login.LoginActivity;
import com.simpleaccount.Toast.ToastUtils;
import com.simpleaccount.User.AppUser;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BatchResult;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.CountListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by zhou on 2017/7/21.
 * 有关云端的增删查改操作集合
 */

public class CloudOperations {
    //添加数据到云端
    //批量添加
    static Integer cnt = 0;
    static final int UPLOAD_CNT=40;
    static final int DOWNLOAD_CNT=100;

    public static void batchUpload(final Context context, final List<Entry> entries) {//batchAdd
        AppUser userInfo = BmobUser.getCurrentUser(AppUser.class);
        if (userInfo == null) {
            ToastUtils.toast(context, "请先登录", "warning");
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
            return;
        }


        int cnt = entries.size();
        int i = 0;
        int size = 0;
        while (size < cnt) {
            List<BmobObject> bills = new ArrayList<BmobObject>();
            size = size + UPLOAD_CNT > cnt ? cnt : size + UPLOAD_CNT;
            for (; i < size; i++) {//for loop
                Entry entry = entries.get(i);
                if (entry.getObjectId() == null) {
                    Bill bill = new Bill();
                    bill.setUsername(userInfo.getUsername());
                    bill.setId(entry.getId());
                    bill.setMoney(entry.getMoney());
                    bill.setCategory(entry.getCategory());
                    BmobDate date = new BmobDate(entry.getDate());
                    bill.setDate(date);
                    bill.setMsg(entry.getMsg());
                    bills.add(bill);
                }
            }
            final int finalI = i;
            new BmobBatch().insertBatch(bills).doBatch(new QueryListListener<BatchResult>() {
                @Override
                public void done(List<BatchResult> o, BmobException e) {//done 1
                    if (e == null) {
                        for (int i = 0; i < o.size(); i++) {//for
                            BatchResult result = o.get(i);
                            BmobException ex = result.getError();
                            if (ex == null) {//ife
                                Entry entry = entries.get(i + finalI - 50);
                                entry.setObjectId(result.getObjectId());
                                DbUtils.modifyEntry(entry);
                            } else {
                                Log.e("bmob", ("upload fail" + i) + (finalI - 50));
                            }
                        }
                    } else {
                        ToastUtils.toast(context, "上传失败", "err");
                        Log.e("bmob", "上传失败" + e.getErrorCode() + e.getMessage());
                    }
                }
            });
        }
    }//batchAdd

    //单条添加
    public static void singleUpload(int id, final Context context) {//single insert
        AppUser user = BmobUser.getCurrentUser(AppUser.class);
        if (user == null) {//判断未登录
            return;
        }//判断未登录
        else {//else login
            String user1 = (String) AppUser.getObjectByKey("username");
            Bill bill = new Bill();
            //导入数据
            final Entry entry = DbUtils.getEntryById(id);

            if (entry.getObjectId() != null && !entry.getObjectId().equals("")) {
                Log.e( "bmob", "数据已存在");

            } else {//else
                bill.setUsername(user1);
                bill.setId(entry.getId());
                bill.setMoney(entry.getMoney());
                bill.setCategory(entry.getCategory());
                BmobDate date = new BmobDate(entry.getDate());
                bill.setDate(date);
                bill.setMsg(entry.getMsg());
                bill.save(new SaveListener<String>() {//save
                    @Override
                    public void done(String objectId, BmobException e) {//done 1
                        if (e == null) {
                            entry.setObjectId(objectId);
                            DbUtils.modifyEntry(entry);
//                            ToastUtils.toast(context, "上传成功", "success");
                        } else {
//                            ToastUtils.toast(context, "上传失败", "err");
                        }
                    }
                });
            }
        }
    }

    //删除操作
    public static void singleDelete(int id, final Context context) {
        AppUser user = BmobUser.getCurrentUser(AppUser.class);
        if (user == null) {
            return;
        }
        else {

            Entry entry1 = DbUtils.getEntryById(id);
            if (entry1.getObjectId() == null || entry1.getObjectId().equals("")) {
                return;
            }
            entry1.setObjectId(entry1.getObjectId());
            entry1.delete(new UpdateListener() {//delete
                @Override
                public void done(BmobException e) {//done
                    if (e == null) {

                    }
                    else {
//                        ToastUtils.toast(context, "删除云端数据失败", "err");
                        Log.e("bmob","删除失败");
                    }
                }//done
            });
        }
    }


    //查询数据内容,一次查询50条并按日期降序排列（包括将查下来的数据的Id修改使他们的Id和本地原有的数据的Id不同）

    public static void batchDownload(final Context context) {//query

        AppUser appUser = BmobUser.getCurrentUser(AppUser.class);
        if (appUser == null) {//if login
            ToastUtils.toast(context, "请先登录", "warning");
            return;
        }
        final String userName = appUser.getUsername();
        BmobQuery<Bill> query1 = new BmobQuery<Bill>();
        query1.addWhereEqualTo("username", userName);

        query1.count(Bill.class, new CountListener() {
            @Override
            public void done(Integer integer, BmobException e) {
                if (e == null) {
                    cnt = integer;
                    Log.e("bmob", "数量为：" + integer);
                    int curPage = 0;
                    int size = 0;
                    BmobQuery<Bill> query = new BmobQuery<>();
                    query.addWhereEqualTo("username", userName);
                    query.order("-date");
                    query.setLimit(DOWNLOAD_CNT);
                    while (size < cnt) {
                        size = size + DOWNLOAD_CNT > cnt ? cnt : size + DOWNLOAD_CNT;

                        query.findObjects(new FindListener<Bill>() {//find object
                            @Override
                            public void done(List<Bill> list, BmobException e) {//done
                                if (e == null) {//if e==null
                                    //显示成功信息
                                    int cnt = DbUtils.getCount();
                                    for (int i = 0; i < list.size(); i++) {
                                        Bill bill = list.get(i);
                                        Category category = DbUtils.getCategory(bill.getCategory());
                                        long date = BmobDate.getTimeStamp(bill.getDate().getDate());
                                        Entry entry = new Entry(cnt + i, bill.getMoney(), category, new Date(date), bill.getMsg());
                                        entry.setObjectId(bill.getObjectId());
                                        DbUtils.insertEntry(entry);
                                    }
                                    Log.e("bmob", "下载成功");
                                } else {
                                    ToastUtils.toast(context, "查询失败", "err");
                                }
                            }//done
                        });
                        curPage++;
                        query.setSkip(curPage * DOWNLOAD_CNT);
                    }
                } else {
                    Log.e("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });


    }//query


    //修改更新云端数据
    public void singleUpdate(int id, final Context context) {
        AppUser user = BmobUser.getCurrentUser(AppUser.class);
        if (user == null) {
            ToastUtils.toast(context, "请先登录", "warning");
            Intent intent3 = new Intent(context, LoginActivity.class);
            context.startActivity(intent3);
        } else {
            Entry entry = DbUtils.getEntryById(id);
            entry.setMoney(entry.getMoney());
            entry.setCategory(entry.getCategory());
            entry.setDate(entry.getDate());
            entry.setMsg(entry.getMsg());

            entry.update(entry.getObjectId(), new UpdateListener() {//update
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        ToastUtils.toast(context, "更新成功", "success");
                    } else {
                        ToastUtils.toast(context, "更新失败", "err");
                    }

                }//done 1
            });
        }
    }


    //一键同步
    public static void SyncData(final Context context) {//sync
        if(BmobUser.getCurrentUser()==null){
            return;
        }
        DbUtils.deleteUploadedEntry();
        List<Entry> entries = DbUtils.getEntries();
        batchDownload(context);
        batchUpload(context, entries);
        Log.e("bmob", "上传的数据：" + entries.size());
        Log.e("bmob", "下载的数据：" + (DbUtils.getCount() - entries.size()));


    }//syncs


}
